﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.SQLite;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using Newtonsoft.Json;
using Sunlight.Dispatch.Dal;
using Sunlight.Dispatch.Model;
using Sunlight.Dispatch.Tools;
using Sunlight.Dispatch.UI.Controls;
using Sunlight.Dispatch.UI.Extensions;
using Sunlight.Dispatch.UI.Properties;
using Sunlight.Dispatch.UI.TimeGranlarityForms;

namespace Sunlight.Dispatch.UI {
    public partial class TinfManagementFrm : BaseFrm {
        public TinfManagementFrm() {
            InitializeComponent();
            this.Load += InterfaceLogFrm_Load;
        }

        private void InterfaceLogFrm_Load(object sender, EventArgs e) {
            var keyValueItems = JsonConvert.DeserializeObject<List<KeyValueItem>>(Settings.Default.InterfaceStatus);
            this.cmbDispachStatus.DataSource = keyValueItems;
            this.cmbDispachStatus.DisplayMember = "Value";
            this.cmbDispachStatus.ValueMember = "Key";

            this.pagerControl.OnPageChanged += this.PagerControl_OnPageChanged;
            this.OnControlCreated(this.dgvLogInfo, this.pagerControl);
            this.pagerControl.PageSize = 20;
            this.txbBusiness.KeyDown += TxbCommon_KeyDown;
            this.txbBusiness.KeyDown += TxbCommon_KeyDown;
            this.txbKeyWords.KeyDown += TxbCommon_KeyDown;
            this.dgvLogInfo.KeyDown += this.DgvLogInfo_KeyDown;
            this.InitComboBoxForDataBase();
        }

        private void DgvLogInfo_KeyDown(object sender, KeyEventArgs e) {
            if(dgvLogInfo.SelectedRows.Count <= 0)
                return;
            this.tsbDelete.PerformClick();
        }

        private void TxbCommon_KeyDown(object sender, KeyEventArgs e) {
            if(e.KeyCode == Keys.Enter)
                this.SearchGridView(1);
        }

        protected override void LoadInitLocation() {
            base.LoadInitLocation();
            this.dgvLogInfo.Height = this.Height - this.gbCondition.Height - this.pageControlPanel.Height - 90;
            this.dgvLogInfo.Width = this.Width - 50;
            this.dgvLogInfo.ScrollBars = ScrollBars.Vertical;
            this.pageControlPanel.Location = new Point(this.dgvLogInfo.Location.X, this.dgvLogInfo.Location.Y + this.dgvLogInfo.Height);
            this.pageControlPanel.Width = this.dgvLogInfo.Width;
            var locationX = this.dgvLogInfo.Width - this.pagerControl.Width - 50;
            this.pagerControl.Location = new Point(this.pageControlPanel.Location.X + locationX, pagerControl.Location.Y);
        }

        private void PagerControl_OnPageChanged(object sender, PageControlEvemtArgs e) {
            this.SearchGridView(e.PageIndex);
        }

        private void InitComboBoxForDataBase() {
            var config = Utils.DeSerialize();
            if(config == null) {
                return;
            }
            using(var conn = new SQLiteConnection(string.Format($"Data Source={config.SqliteStoryPath};Version=3;"))) {
                conn.Open();
                var sqlExecute = "select Id,Name,ConnectString from ConnectStringConfigTb";
                var command = new SQLiteCommand(sqlExecute, conn);
                var reader = command.ExecuteReader();
                var source = new List<ConnectStringConfigTb>();
                while(reader.Read()) {
                    source.Add(new ConnectStringConfigTb {
                        Id = reader[0].ToString(),
                        Name = reader[1].ToString(),
                        ConnectString = reader[2].ToString()
                    });
                }

                //新增状态的接口配置，不允许编辑，必须在配置规则的情况下可以使用
                this.comboBoxDataBase.DataSource = null;
                this.comboBoxDataBase.DataSource = source;
                this.comboBoxDataBase.DisplayMember = "Name";
                this.comboBoxDataBase.ValueMember = "ConnectString";
            }
        }

        private void SearchGridView(int pageIndex = 1) {
            if(this.comboBoxDataBase.DataSource == null) {
                MessageBoxEx.Show(this, "数据库选项数据源为空，请配置", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if(this.comboBoxDataBase.SelectedItem == null) {
                MessageBoxEx.Show(this, "数据库选项不能为空，请选择", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            var selectedItem = this.comboBoxDataBase.SelectedItem as ConnectStringConfigTb;
            if(selectedItem == null)
                return;
            this.IsLoading = true;
            using(var dataContext = new MonitorSettingDataContext(selectedItem.ConnectString)) {
                IQueryable<TIntf> tinf = dataContext.TIntf;
                IQueryable<TBusiness> business = dataContext.TBusiness;
                var result = from inf in tinf
                             join bus in business on inf.BusinessCode equals bus.Code into temp
                             from tt in temp.DefaultIfEmpty()
                             select new InfoViewModel {
                                 Id = inf.ID,
                                 Code = inf.Code,
                                 Name = inf.Name,
                                 Uper = inf.Uper,
                                 UpFunction = inf.UpFunction,
                                 BlnStep = inf.blnStep == 1 ? "是" : "否",
                                 Downer = inf.Downer,
                                 DownFunction = inf.DownFunction,
                                 MaxNum = inf.MaxNum,
                                 ThreadNum = inf.ThreadNum,
                                 BusinessCode = inf.BusinessCode,
                                 BusinessName = tt.Name,
                                 Memo = inf.Memo,
                                 Class = inf.Class,
                                 DataClass = inf.DataClass,
                                 CompleteMethod = inf.CompleteMethod,
                                 Sequential = inf.Sequential,
                                 Status = inf.Status,
                                 DsplayStatus = inf.Status == 0 ? "暂停" : (inf.Status == 1 ? "运行" : ""),
                                 ConnectString = selectedItem.ConnectString
                             };

                var methodName = this.txbMethod.Text;
                var businessCategory = this.txbBusiness.Text;
                var keyWords = this.txbKeyWords.Text;
                var dispachStatus = this.cmbDispachStatus.SelectedValue as int?;

                if(!string.IsNullOrEmpty(methodName)) {
                    result = result.Where(d => d.UpFunction.ToLower().Contains(methodName.ToLower()));
                }
                if(!string.IsNullOrEmpty(businessCategory)) {
                    result = result.Where(d => d.BusinessCode.ToLower().Contains(businessCategory.ToLower()) || d.BusinessName.ToLower().Contains(businessCategory.ToLower()));
                }


                if(!string.IsNullOrEmpty(keyWords)) {
                    result = result.Where(d => d.UpFunction.ToLower().Contains(keyWords.ToLower())
                                               || d.Code.ToLower().Contains(keyWords.ToLower())
                                               || d.Name.ToLower().Contains(keyWords.ToLower())
                                               || d.Uper.ToLower().Contains(keyWords.ToLower())
                                               || d.DownFunction.ToLower().Contains(keyWords.ToLower())
                                               || d.Downer.ToLower().Contains(keyWords.ToLower())
                                               || d.BusinessCode.ToLower().Contains(keyWords.ToLower())
                                               || d.CompleteMethod.ToLower().Contains(keyWords.ToLower())
                                               || d.BusinessName.ToLower().Contains(keyWords.ToLower()));
                }

                if(dispachStatus != -1) {
                    result = result.Where(d => d.Status == dispachStatus);
                }

                var recordCount = result.Count();
                var data = result.OrderBy(d => d.Id).Skip((pageIndex - 1) * this.pagerControl.PageSize).Take(this.pagerControl.PageSize).ToList();

                this.dgvLogInfo.DataSource = data;
                this.pagerControl.PageIndex = pageIndex;
                this.pagerControl.DrawControl(recordCount);
                this.IsLoading = false;
            }
        }

        private void btnSearch_Click_1(object sender, EventArgs e) {
            SearchGridView();
        }

        private void tsbDelete_Click(object sender, EventArgs e) {
            if(dgvLogInfo.SelectedRows.Count <= 0)
                return;
            if(MessageBoxEx.Show(this, "确定要删除所选择的数据吗？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk) != DialogResult.OK)
                return;
            var infoViewModel = this.dgvLogInfo.SelectedRows.Cast<DataGridViewRow>().Select(d => d.DataBoundItem).Cast<InfoViewModel>().FirstOrDefault();
            if(infoViewModel == null)
                return;
            this.dgvLogInfo.Cursor = Cursors.WaitCursor;
            var context = new MonitorSettingDataContext(infoViewModel.ConnectString);

            var result = context.TIntf.Include("TRule.TRuleList").FirstOrDefault(data => data.ID == infoViewModel.Id);
            if(result == null) {
                this.dgvLogInfo.Cursor = Cursors.Default;
                return;
            }
            try {
                //暂时不清楚为何不能级联删除
                context.TRuleList.DeleteAllOnSubmit(result.TRule.SelectMany(d => d.TRuleList));
                context.SubmitChanges();
                context.TRule.DeleteAllOnSubmit(result.TRule);
                context.SubmitChanges();
                context.TIntf.DeleteOnSubmit(result);
                context.SubmitChanges();
                MessageBoxEx.Show(this, "删除成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.SearchGridView();
            } catch(Exception exception) {
                MessageBoxEx.Show(this, exception.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            } finally {
                this.dgvLogInfo.Cursor = Cursors.Default;
                context.Dispose();
            }
        }

        private void btnRefresh_Click(object sender, EventArgs e) {
            this.comboBoxDataBase.Cursor = Cursors.WaitCursor;
            this.InitComboBoxForDataBase();
            this.comboBoxDataBase.Cursor = Cursors.Default;
        }

        private void toolStripButtonStart_Click(object sender, EventArgs e) {
            SetRunStatus((int)RunStatus.启动);
        }

        private void SetRunStatus(short runStatus) {
            if(dgvLogInfo.SelectedRows.Count <= 0)
                return;
            if(MessageBoxEx.Show(this, $"确定要{Enum.GetName(typeof(RunStatus), runStatus)}所选择的数据吗？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk) != DialogResult.OK)
                return;
            var infoViewModel = this.dgvLogInfo.SelectedRows.Cast<DataGridViewRow>().Select(d => d.DataBoundItem).Cast<InfoViewModel>().FirstOrDefault();
            if(infoViewModel == null)
                return;
            this.dgvLogInfo.Cursor = Cursors.WaitCursor;
            var context = new MonitorSettingDataContext(infoViewModel.ConnectString);

            var result = context.TIntf.FirstOrDefault(data => data.ID == infoViewModel.Id);
            if(result == null) {
                this.dgvLogInfo.Cursor = Cursors.Default;
                return;
            }
            result.Status = runStatus;
            try {
                context.SubmitChanges();
                MessageBoxEx.Show(this, $"所选择{Enum.GetName(typeof(RunStatus), runStatus)}成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.SearchGridView();
            } catch(Exception ex) {
                MessageBoxEx.Show(this, ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            } finally {
                this.dgvLogInfo.Cursor = Cursors.Default;
                context.Dispose();
            }
        }

        private void toolStripButtonStop_Click(object sender, EventArgs e) {
            SetRunStatus((int)RunStatus.暂停);
        }

        private void toolStripButtonSetting_Click(object sender, EventArgs e) {
            if(dgvLogInfo.SelectedRows.Count <= 0)
                return;
            var frm = new GranlaritySelectFrm();
            frm.ExtendEvent += Frm_ExtendEvent;
            frm.ShowDialog();
        }

        private void Frm_ExtendEvent(object sender, SubmittedEventArgs e) {
            var keyValue = sender as KeyValueItem;
            if(dgvLogInfo.SelectedRows.Count <= 0|| keyValue==null)
                return;

            var infoViewModel = this.dgvLogInfo.SelectedRows.Cast<DataGridViewRow>().Select(d => d.DataBoundItem).Cast<InfoViewModel>().FirstOrDefault();
            if(infoViewModel == null)
                return;
            BaseEditFrm frm;
            switch(keyValue.Key) {
                case (int)TimeGranlarity.周:
                    frm = new SettingByWeekFrm();
                    
                    break;
                case (int)TimeGranlarity.日:
                    frm = new SettingByDayFrm();
                    break;
                case (int)TimeGranlarity.月:
                    frm = new SettingByMonthFrm();
                    break;
                case (int)TimeGranlarity.年:
                    frm = new SettingByYearFrm();
                    break;
                default:
                    frm = new SettingByDayFrm();
                    break;
            }
            frm.SetObjectToEditById(infoViewModel.Id, infoViewModel.ConnectString);
            frm.ExtendEvent += this.Frm_ExtendEvent;
            frm.MdiParent = this.MdiParent;
            frm.Show();
        }
    }
}
